package com.example.crossborderecommerce.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.crossborderecommerce.entity.*;
import com.example.crossborderecommerce.mapper.CustomerMapper;
import com.example.crossborderecommerce.service.ICustomerService;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 客户模块
 *
 * @author Yolanda
 * @since 2024-05-09
 */
@RestController
@Transactional
@RequestMapping("/customer")
public class CustomerController {
    @Resource
    ICustomerService customerService;
    @Resource
    CustomerMapper customerMapper;

    /**
     * 添加客户
     * @param customer
     * @return
     */
    @PostMapping("/save")
    public Result save(@RequestBody Customer customer) {
        boolean res = customerService.save(customer);
        if(res) {
            return Result.success("添加客户成功！");
        }
        return Result.error("添加客户失败！");
    }
    /**
     * 删除客户
     * @param customer
     * @return
     */
    @PostMapping("/delete")
    public Result delete(@RequestBody Customer customer) {
        boolean res = customerService.removeById(customer);
        if(res) {
            return Result.success("删除客户成功！");
        }
        return Result.error("删除客户失败！");
    }

    /**
     * 查询所有客户
     * @return
     */
    @GetMapping("/findAll")
    public Result findAll() {
        List<Customer> customerList = customerService.list();
        if(customerList != null) {
            return Result.success("查询所有客户成功！", customerList);
        }
        return Result.error("查询所有客户失败！");
    }

    /**
     * 分页查询所有客户信息
     * @param username
     * @param pageNum
     * @param pageSize
     * @return
     */
    @GetMapping("/findPage")
    public Result findPage(@RequestParam(defaultValue = "") String username,
                           @RequestParam Integer pageNum,
                           @RequestParam Integer pageSize){
        QueryWrapper<Customer> queryWrapper = new QueryWrapper<>();
        queryWrapper.like("username", username);
        Page<Customer> customerPage = customerService.page(new Page<>(pageNum,pageSize), queryWrapper);
        return Result.success("成功查询所有客户！", customerPage);
    }

    /**
     * 导出客户信息
     * @param username
     * @param response
     * @return
     */
    @GetMapping("exportCustomerList")
    public Result exportCustomerList(@RequestParam(defaultValue = "") String username,
                                         HttpServletResponse response) {
        QueryWrapper<Customer> queryWrapper = new QueryWrapper<>();
        List<Customer> customerList = customerService.list(queryWrapper);
        HSSFWorkbook wb = new HSSFWorkbook(); // 导出到excel文件中
        HSSFSheet sheet = wb.createSheet("表一");
        HSSFRow row = sheet.createRow(0);
        HSSFCellStyle style = wb.createCellStyle();
        style.setAlignment(HorizontalAlignment.CENTER);
        HSSFCell cell = row.createCell((short) 0);
        cell.setCellValue("ID");
        cell.setCellStyle(style);
        cell = row.createCell((short) 1);
        cell.setCellValue("用户名");
        cell.setCellStyle(style);
        cell = row.createCell((short) 2);
        cell.setCellValue("姓名");
        cell.setCellStyle(style);
        cell = row.createCell((short) 3);
        cell.setCellValue("联系电话");
        cell.setCellStyle(style);
        cell = row.createCell((short)4);
        cell.setCellValue("国家");
        cell.setCellStyle(style);
        cell = row.createCell((short)5);
        cell.setCellValue("地址");
        cell.setCellStyle(style);
        for (int i = 0; i < customerList.size(); i++) {
            row = sheet.createRow(i + 1);
            Customer customer= customerList.get(i);
            row.createCell((short) 0).setCellValue(customer.getId());
            row.createCell((short) 1).setCellValue(customer.getUsername());
            row.createCell((short) 2).setCellValue(customer.getName());
            row.createCell((short) 3).setCellValue(customer.getPhone());
            row.createCell((short) 4).setCellValue(customer.getNation());
            row.createCell((short) 5).setCellValue(customer.getAddress());
        }
        String fileName = "exportCustomerList.xls";
        // 用户下载
        try {
            ServletOutputStream outputStream = null;
            response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
            response.setHeader("Content-Disposition", "attachment;filename="+ URLEncoder.encode(fileName, "UTF-8"));
            outputStream = response.getOutputStream();
            wb.write(outputStream);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return Result.success("exportCustomerList");
    }
    /**
     * 删除一系列客户
     * @param ids
     * @return
     */
    @GetMapping("/deleteBatch")
    public Result deleteBatch(@RequestParam String ids) {
        List<String> customerIds = Arrays.stream(ids.split(",")).collect(Collectors.toList());
        boolean res = customerService.removeByIds(customerIds);
        if(res) {
            return Result.success("删除客户成功！");
        }
        return Result.error("删除客户失败！");
    }

    /**
     * 修改客户
     * @param customer
     * @return
     */
    @PostMapping("/update")
    public Result update(@RequestBody Customer customer) {
        boolean res = customerService.saveOrUpdate(customer);
        if (res) {
            return Result.success("修改客户成功！");
        }
        return Result.error("修改客户失败！");
    }

    /**
     * 获取目前顾客的所有国家
     * @return
     */
    @GetMapping("/getAllNation")
    public Result getAllNation() {
        return Result.success(customerMapper.getAllNations());
    }

    /**
     * 获取目前顾客的所有国家
     * @param nation
     * @return
     */
    @GetMapping("/getCustomerCountByNation")
    public Result getCustomerCountByNation(@RequestParam("nation") String nation) {
        return Result.success(customerMapper.getCustomerCountByNation(nation));
    }
}
